import 'package:flutter/material.dart';

/// 页面状态枚举
enum PageState {
  loading,
  success,
  error,
  empty,
}

/// 增强状态组件配置
class StateWidgetConfig {
  /// 加载组件
  final Widget? loadingWidget;

  /// 错误组件构建器
  final Widget Function(String error, VoidCallback? retry)? errorBuilder;

  /// 空状态组件
  final Widget? emptyWidget;

  /// 是否显示重试按钮
  final bool showRetry;

  /// 动画持续时间
  final Duration animationDuration;

  /// 是否启用动画
  final bool enableAnimation;

  const StateWidgetConfig({
    this.loadingWidget,
    this.errorBuilder,
    this.emptyWidget,
    this.showRetry = true,
    this.animationDuration = const Duration(milliseconds: 300),
    this.enableAnimation = true,
  });
}

/// 增强状态组件
class EnhancedStateWidget extends StatelessWidget {
  /// 当前状态
  final PageState state;

  /// 成功时显示的组件
  final Widget child;

  /// 错误信息
  final String? errorMessage;

  /// 重试回调
  final VoidCallback? onRetry;

  /// 配置
  final StateWidgetConfig config;

  const EnhancedStateWidget({
    Key? key,
    required this.state,
    required this.child,
    this.errorMessage,
    this.onRetry,
    this.config = const StateWidgetConfig(),
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (config.enableAnimation) {
      return AnimatedSwitcher(
        duration: config.animationDuration,
        child: _buildContent(context),
      );
    }

    return _buildContent(context);
  }

  Widget _buildContent(BuildContext context) {
    switch (state) {
      case PageState.loading:
        return _buildLoadingWidget(context);
      case PageState.error:
        return _buildErrorWidget(context);
      case PageState.empty:
        return _buildEmptyWidget(context);
      case PageState.success:
        return child;
    }
  }

  /// 构建加载组件
  Widget _buildLoadingWidget(BuildContext context) {
    if (config.loadingWidget != null) {
      return config.loadingWidget!;
    }

    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text(
            '加载中...',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建错误组件
  Widget _buildErrorWidget(BuildContext context) {
    if (config.errorBuilder != null) {
      return config.errorBuilder!(errorMessage ?? '发生错误', onRetry);
    }

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red.shade300,
          ),
          const SizedBox(height: 16),
          Text(
            errorMessage ?? '发生错误',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
                  color: Colors.grey.shade600,
                ),
            textAlign: TextAlign.center,
          ),
          if (config.showRetry && onRetry != null) ...[
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建空状态组件
  Widget _buildEmptyWidget(BuildContext context) {
    if (config.emptyWidget != null) {
      return config.emptyWidget!;
    }

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 64,
            color: Colors.grey.shade300,
          ),
          const SizedBox(height: 16),
          Text(
            '暂无数据',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
                  color: Colors.grey.shade600,
                ),
          ),
        ],
      ),
    );
  }
}

/// 下拉刷新状态组件
class PullToRefreshStateWidget extends StatefulWidget {
  /// 当前状态
  final PageState state;

  /// 成功时显示的组件
  final Widget child;

  /// 错误信息
  final String? errorMessage;

  /// 刷新回调
  final Future<void> Function()? onRefresh;

  /// 重试回调
  final VoidCallback? onRetry;

  /// 配置
  final StateWidgetConfig config;

  const PullToRefreshStateWidget({
    Key? key,
    required this.state,
    required this.child,
    this.errorMessage,
    this.onRefresh,
    this.onRetry,
    this.config = const StateWidgetConfig(),
  }) : super(key: key);

  @override
  State<PullToRefreshStateWidget> createState() =>
      _PullToRefreshStateWidgetState();
}

class _PullToRefreshStateWidgetState extends State<PullToRefreshStateWidget> {
  @override
  Widget build(BuildContext context) {
    if (widget.state == PageState.success && widget.onRefresh != null) {
      return RefreshIndicator(
        onRefresh: widget.onRefresh!,
        child: widget.child,
      );
    }

    return EnhancedStateWidget(
      state: widget.state,
      errorMessage: widget.errorMessage,
      onRetry: widget.onRetry,
      config: widget.config,
      child: widget.child,
    );
  }
}

/// 分页加载组件
class PaginatedStateWidget extends StatefulWidget {
  /// 当前状态
  final PageState state;

  /// 子组件
  final Widget child;

  /// 是否有更多数据
  final bool hasMore;

  /// 是否正在加载更多
  final bool isLoadingMore;

  /// 加载更多回调
  final VoidCallback? onLoadMore;

  /// 滚动控制器
  final ScrollController? scrollController;

  /// 触发加载更多的距离阈值
  final double loadMoreThreshold;

  const PaginatedStateWidget({
    Key? key,
    required this.state,
    required this.child,
    required this.hasMore,
    this.isLoadingMore = false,
    this.onLoadMore,
    this.scrollController,
    this.loadMoreThreshold = 200,
  }) : super(key: key);

  @override
  State<PaginatedStateWidget> createState() => _PaginatedStateWidgetState();
}

class _PaginatedStateWidgetState extends State<PaginatedStateWidget> {
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = widget.scrollController ?? ScrollController();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    if (widget.scrollController == null) {
      _scrollController.dispose();
    } else {
      _scrollController.removeListener(_onScroll);
    }
    super.dispose();
  }

  void _onScroll() {
    if (!widget.hasMore || widget.isLoadingMore) return;

    final position = _scrollController.position;
    final threshold = position.maxScrollExtent - widget.loadMoreThreshold;

    if (position.pixels >= threshold) {
      widget.onLoadMore?.call();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(child: widget.child),
        if (widget.isLoadingMore)
          Container(
            padding: const EdgeInsets.all(16),
            child: const Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2),
                ),
                SizedBox(width: 8),
                Text(
                  '加载更多...',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ),
      ],
    );
  }
}

/// 骨架屏组件
class SkeletonWidget extends StatefulWidget {
  /// 宽度
  final double? width;

  /// 高度
  final double? height;

  /// 边框半径
  final double borderRadius;

  /// 是否启用动画
  final bool enableAnimation;

  /// 动画持续时间
  final Duration animationDuration;

  /// 基础颜色
  final Color? baseColor;

  /// 高亮颜色
  final Color? highlightColor;

  const SkeletonWidget({
    Key? key,
    this.width,
    this.height,
    this.borderRadius = 4,
    this.enableAnimation = true,
    this.animationDuration = const Duration(milliseconds: 1000),
    this.baseColor,
    this.highlightColor,
  }) : super(key: key);

  @override
  State<SkeletonWidget> createState() => _SkeletonWidgetState();
}

class _SkeletonWidgetState extends State<SkeletonWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();

    if (widget.enableAnimation) {
      _animationController = AnimationController(
        duration: widget.animationDuration,
        vsync: this,
      );

      _animation = Tween<double>(
        begin: 0.0,
        end: 1.0,
      ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      ));

      _animationController.repeat(reverse: true);
    }
  }

  @override
  void dispose() {
    if (widget.enableAnimation) {
      _animationController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final baseColor = widget.baseColor ?? Colors.grey.shade300;
    final highlightColor = widget.highlightColor ?? Colors.grey.shade100;

    Widget skeleton = Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        color: baseColor,
        borderRadius: BorderRadius.circular(widget.borderRadius),
      ),
    );

    if (widget.enableAnimation) {
      skeleton = AnimatedBuilder(
        animation: _animation,
        builder: (context, child) {
          return Container(
            width: widget.width,
            height: widget.height,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [
                  baseColor,
                  Color.lerp(baseColor, highlightColor, _animation.value)!,
                  baseColor,
                ],
                stops: const [0.0, 0.5, 1.0],
              ),
              borderRadius: BorderRadius.circular(widget.borderRadius),
            ),
          );
        },
      );
    }

    return skeleton;
  }
}

/// 骨架屏列表组件
class SkeletonList extends StatelessWidget {
  /// 项目数量
  final int itemCount;

  /// 项目高度
  final double itemHeight;

  /// 项目间距
  final double spacing;

  /// 内边距
  final EdgeInsets? padding;

  /// 骨架屏配置
  final SkeletonWidget Function(int index)? itemBuilder;

  const SkeletonList({
    Key? key,
    this.itemCount = 5,
    this.itemHeight = 80,
    this.spacing = 16,
    this.padding,
    this.itemBuilder,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      padding: padding,
      itemCount: itemCount,
      separatorBuilder: (context, index) => SizedBox(height: spacing),
      itemBuilder: (context, index) {
        if (itemBuilder != null) {
          return itemBuilder!(index);
        }

        return SkeletonWidget(
          width: double.infinity,
          height: itemHeight,
          borderRadius: 8,
        );
      },
    );
  }
}

/// 骨架屏网格组件
class SkeletonGrid extends StatelessWidget {
  /// 项目数量
  final int itemCount;

  /// 列数
  final int crossAxisCount;

  /// 宽高比
  final double childAspectRatio;

  /// 主轴间距
  final double mainAxisSpacing;

  /// 交叉轴间距
  final double crossAxisSpacing;

  /// 内边距
  final EdgeInsets? padding;

  const SkeletonGrid({
    Key? key,
    this.itemCount = 6,
    this.crossAxisCount = 2,
    this.childAspectRatio = 1,
    this.mainAxisSpacing = 16,
    this.crossAxisSpacing = 16,
    this.padding,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: padding,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        childAspectRatio: childAspectRatio,
        mainAxisSpacing: mainAxisSpacing,
        crossAxisSpacing: crossAxisSpacing,
      ),
      itemCount: itemCount,
      itemBuilder: (context, index) {
        return const SkeletonWidget(
          width: double.infinity,
          height: double.infinity,
          borderRadius: 8,
        );
      },
    );
  }
}

/// 智能刷新组件
class SmartRefreshWidget extends StatefulWidget {
  /// 子组件
  final Widget child;

  /// 刷新回调
  final Future<void> Function()? onRefresh;

  /// 加载更多回调
  final Future<void> Function()? onLoadMore;

  /// 是否启用下拉刷新
  final bool enablePullDown;

  /// 是否启用上拉加载
  final bool enablePullUp;

  /// 是否有更多数据
  final bool hasMore;

  /// 刷新指示器构建器
  final Widget Function()? refreshIndicatorBuilder;

  /// 加载指示器构建器
  final Widget Function()? loadingIndicatorBuilder;

  const SmartRefreshWidget({
    Key? key,
    required this.child,
    this.onRefresh,
    this.onLoadMore,
    this.enablePullDown = true,
    this.enablePullUp = true,
    this.hasMore = true,
    this.refreshIndicatorBuilder,
    this.loadingIndicatorBuilder,
  }) : super(key: key);

  @override
  State<SmartRefreshWidget> createState() => _SmartRefreshWidgetState();
}

class _SmartRefreshWidgetState extends State<SmartRefreshWidget> {
  @override
  Widget build(BuildContext context) {
    Widget child = widget.child;

    // 包装下拉刷新
    if (widget.enablePullDown && widget.onRefresh != null) {
      child = RefreshIndicator(
        onRefresh: widget.onRefresh!,
        child: child,
      );
    }

    return child;
  }
}
